# coding: utf-8
import os
import sys

BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
print(os.path.abspath(__file__))
print(BASE_DIR)
sys.path.extend([BASE_DIR,])
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "finance_c2c.settings")

import django

django.setup()

from core.wchat.models import WxMenu
from core.wchat.wx_base import WxBase


def select_menu_form_db():
    """
    从数据库中获取微信公众号菜单
    :return: 公众号菜单
    """
    button_list = []
    menu_info = WxMenu.objects.all()
    for i in menu_info:
        button_data = {"name": i.name}
        if i.type == "None" or i.type == "主菜单":
            sub_button = []
            child_menu_info = i.wxmenuchild_set.all()
            for one_child_menu in child_menu_info:
                sub_button_data = {
                    "type": str(one_child_menu.type),
                    "name": one_child_menu.name,
                    one_child_menu.key: str(one_child_menu.key_or_url)
                }
                sub_button.append(sub_button_data)
            button_data["sub_button"] = sub_button
        else:
            button_data["type"] = str(i.type)
            button_data[i.key] = str(i.key_or_url)
        button_list.append(button_data)
    menu_data = {"button": button_list}
    print(menu_data)
    return menu_data


def create_menu():
    wx_base = WxBase()
    info = select_menu_form_db()
    wx_base.client.menu.create(info)


if __name__ == '__main__':
    print(create_menu())
